/* eslint-disable indent */
'use strict';

const Controller = require('egg').Controller;
const mongoose = require("mongoose");

class CommentController extends Controller {
  /**
   * 创建评论
   * @param {string} content
   * @param {number} type
   * @param {ObjectId} sender
   */
  async createComment() {
    const { ctx } = this;
    console.log("body:", ctx.request.body);
    const { body } = ctx.request;
    const { content, type = 0, sender: senderIdStr = "61793fcd45c2dbfa30e709c1" } = body;
    if (!content || !senderIdStr)
      ctx.body = { code: -1, message: "检查参数" };
    else {
      const senderId = mongoose.Types.ObjectId(senderIdStr);
      const comment = { content, type, sender: senderId, thumbsUp: 0 };
      const sender = await ctx.model.User.find({ _id: senderId });
      if (!sender.length) ctx.body = { code: -2, message: "查无此人" };
      else {
        console.log("sender:", sender);
        console.log("comment:", comment);
        const item = await ctx.model.Comment.create(comment);
        console.log("result:", item);
        if (item) {
          const payload = { ...comment, sender, _id: item._id };
          console.log("payload:", payload);
          ctx.body = { code: 0, payload };
        } else ctx.body = { code: -3, message: '创建失败' };
      }
    }
  }
  async queryComment() {
    const { ctx } = this;
    let { limit } = ctx.query;
    limit = Number(limit);

    // const comments = await ctx.model.Comment.find().limit(isNaN(limit) ? 20 : limit);
    const comments = await ctx.model.Comment.aggregate([
      {
        $lookup: {
          from: 'user',
          localField: 'sender',
          foreignField: '_id',
          as: 'sender'
        }
      },
      { $limit: isNaN(limit) ? 20 : limit },
      { $sort: { _id: -1 } }
    ]);
    console.log("comments:", comments);
    ctx.body = { comments };
  }
  async thumbsUp() {
    const { ctx } = this;
    const { _id } = ctx.request.body;
    const item = await ctx.model.Comment.update({ _id }, {
      $inc: { thumbsUp: 1 }
    });
    console.log(item);
    if (item.ok) {
      ctx.body = { code: 0, message: '点赞成功' }
    } else ctx.body = { code: -1, message: '这都能失败' }
  }
}

module.exports = CommentController;
